from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.routing import APIRouter

from app.core.config import settings
from app.routes import auth, shortener, analytics
from app.schemas.shortener import URLResponse

app = FastAPI(
    title=settings.PROJECT_NAME,
    version=settings.VERSION
)

# CORS设置
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 健康检查端点
@app.get("/api/v1/health")
async def health_check():
    return {"status": "healthy"}

# API路由
app.include_router(auth.router, prefix=f"{settings.API_V1_STR}/auth", tags=["auth"])
app.include_router(analytics.router, prefix=f"{settings.API_V1_STR}/analytics", tags=["analytics"])

# 创建一个新的路由器用于API
api_router = APIRouter(prefix=f"{settings.API_V1_STR}/urls", tags=["urls"])
api_router.post("/shorten", response_model=URLResponse)(shortener.create_short_url)

# 创建一个新的路由器用于重定向
redirect_router = APIRouter(tags=["redirect"])
redirect_router.get("/{short_code}")(shortener.redirect_to_url)

# 注册路由器
app.include_router(api_router)
app.include_router(redirect_router)

@app.get("/")
async def root():
    return {
        "message": "Welcome to URL Shortener API",
        "docs_url": "/docs"
    }